//
//  CartView.swift
//  aishop
//
//  Created by tuguowei on 2025/10/15.
//

import SwiftUI
import Combine

struct CartView: View {
    @StateObject private var viewModel = CartViewModel()
    @State private var isAllSelected: Bool = false
    
    var body: some View {
        NavigationView {
            ZStack(alignment: .bottom) {
                VStack(spacing: 0) {
                    // 顶部标题栏
                    HStack {
                        Spacer()
                        Text("购物车")
                            .font(.headline)
                            .fontWeight(.medium)
                            .foregroundColor(.white)
                        Spacer()
                        
                        if !(viewModel.validCartItems.isEmpty && viewModel.invalidCartItems.isEmpty) {
                            Button(action: {
                                // 编辑功能
                                viewModel.isEditing.toggle()
                            }) {
                                Text(viewModel.isEditing ? "完成" : "编辑")
                                    .font(.body)
                                    .foregroundColor(.white)
                            }
                            .padding(.trailing, 16)
                            .offset(x: 16)
                        }
                    }
                    .padding(.vertical, 12)
                    .background(Color.green)
                    
                    // 共0件商品
                    if viewModel.validCartItems.isEmpty && viewModel.invalidCartItems.isEmpty {
                        Text("共0件商品")
                            .font(.subheadline)
                            .foregroundColor(.white)
                            .frame(maxWidth: .infinity, alignment: .leading)
                            .padding(.horizontal, 16)
                            .padding(.vertical, 8)
                            .background(Color.green)
                    }
                    
                    // 主要内容区域
                    ScrollView {
                        LazyVStack(spacing: 12) {
                            if viewModel.validCartItems.isEmpty && viewModel.invalidCartItems.isEmpty {
                                // 空购物车内容
                                EmptyCartContentView()
                                    .padding(.top, 20)
                            } else {
                                // 有效商品区域
                                if !viewModel.validCartItems.isEmpty {
                                    VStack(alignment: .leading, spacing: 0) {
                                        // 有效商品标题
                                        HStack {
                                            Text("有效商品")
                                                .font(.headline)
                                                .foregroundColor(.primary)
                                            Spacer()
                                        }
                                        .padding(.horizontal, 16)
                                        .padding(.vertical, 10)
                                        .background(Color.white)
                                        
                                        // 有效商品列表
                                        ForEach(viewModel.validCartItems, id: \.id) { item in
                                            CartItemCardView(
                                                item: item,
                                                isSelected: viewModel.isItemSelected(item),
                                                isEditing: viewModel.isEditing,
                                                onToggleSelection: {
                                                    viewModel.toggleItemSelection(item)
                                                },
                                                onQuantityChanged: { newQuantity in
                                                    viewModel.updateItemQuantity(item, newQuantity: newQuantity)
                                                },
                                                onSpecTapped: {
                                                    viewModel.showSpecSelection(for: item)
                                                }
                                            )
                                            .padding(.top, 1)
                                        }
                                    }
                                    .background(Color.white)
                                    .cornerRadius(8)
                                    .shadow(color: Color.black.opacity(0.05), radius: 2, x: 0, y: 1)
                                    .padding(.horizontal, 12)
                                    .padding(.top, 12)
                                }
                                
                                // 无效商品区域
                                if !viewModel.invalidCartItems.isEmpty {
                                    VStack(alignment: .leading, spacing: 0) {
                                        // 无效商品标题
                                        HStack {
                                            Text("无效商品")
                                                .font(.headline)
                                                .foregroundColor(.primary)
                                            Spacer()
                                            
                                            Button(action: {
                                                viewModel.clearInvalidItems()
                                            }) {
                                                Text("清空")
                                                    .font(.subheadline)
                                                    .foregroundColor(.gray)
                                            }
                                        }
                                        .padding(.horizontal, 16)
                                        .padding(.vertical, 10)
                                        .background(Color.white)
                                        
                                        // 无效商品列表
                                        ForEach(viewModel.invalidCartItems, id: \.id) { item in
                                            InvalidCartItemView(item: item)
                                                .padding(.top, 1)
                                        }
                                    }
                                    .background(Color.white)
                                    .cornerRadius(8)
                                    .shadow(color: Color.black.opacity(0.05), radius: 2, x: 0, y: 1)
                                    .padding(.horizontal, 12)
                                    .padding(.top, 12)
                                }
                            }
                            
                            // 推荐商品区域 - 始终显示
                            RecommendedProductsView(products: viewModel.recommendedProducts)
                                .padding(.top, 20)
                                .padding(.bottom, 60) // 为底部结算栏留出空间
                        }
                        .padding(.horizontal, 4)
                    }
                    .background(Color(UIColor.systemGroupedBackground))
                }
                
                // 底部结算栏
                if !(viewModel.validCartItems.isEmpty && viewModel.invalidCartItems.isEmpty) {
                    CartBottomBar(
                        isAllSelected: $isAllSelected,
                        totalPrice: viewModel.totalSelectedPrice,
                        totalCount: viewModel.selectedItemsCount,
                        isEditing: viewModel.isEditing,
                        onAllSelectToggle: {
                            isAllSelected.toggle()
                            viewModel.toggleAllSelection(isAllSelected)
                        },
                        onCheckout: {
                            viewModel.proceedToCheckout()
                        },
                        onDelete: {
                            viewModel.deleteSelectedItems()
                        },
                        onAddToFavorites: {
                            viewModel.addSelectedItemsToFavorites()
                        }
                    )
                }
            }
            .navigationBarHidden(true)
            .sheet(isPresented: $viewModel.showingSpecSelection) {
                if let selectedItem = viewModel.itemForSpecSelection {
                    ProductSpecSelectionView(
                        item: selectedItem,
                        onSpecSelected: { newSpec in
                            viewModel.updateItemSpec(selectedItem, newSpec: newSpec)
                        }
                    )
                }
            }
        }
        .task {
            await viewModel.loadCartItems()
            await viewModel.loadRecommendedProducts()
        }
    }
}

// MARK: - 空购物车内容视图
struct EmptyCartContentView: View {
    var body: some View {
        VStack(spacing: 20) {
            Image("noshoper") // 使用资源文件中的noshoper图片
                .resizable()
                .scaledToFit()
                .frame(width: 120, height: 120)
                .padding(.bottom, 10)
            
            Text("购物车为空哦~")
                .font(.title3)
                .fontWeight(.medium)
                .foregroundColor(.primary)
            
            Text("快去挑选心仪的商品吧")
                .font(.body)
                .foregroundColor(.secondary)
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 60)
        .background(Color.white)
        .cornerRadius(12)
        .padding(.horizontal, 16)
    }
}

// MARK: - 购物车商品卡片视图
struct CartItemCardView: View {
    let item: CartItem
    let isSelected: Bool
    let isEditing: Bool
    let onToggleSelection: () -> Void
    let onQuantityChanged: (Int) -> Void
    let onSpecTapped: () -> Void
    
    var body: some View {
        VStack(spacing: 0) {
            HStack(spacing: 12) {
                // 选择按钮
                Button(action: onToggleSelection) {
                    Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")
                        .font(.system(size: 22))
                        .foregroundColor(isSelected ? .blue : .gray)
                }
                .padding(.leading, 4)
                
                // 商品图片
                AsyncImage(url: URL(string: item.productInfo?.image ?? "")) { image in
                    image
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                } placeholder: {
                    Rectangle()
                        .fill(Color.gray.opacity(0.2))
                }
                .frame(width: 80, height: 80)
                .clipShape(RoundedRectangle(cornerRadius: 8))
                
                // 商品信息
                VStack(alignment: .leading, spacing: 4) {
                    Text(item.productInfo?.storeName ?? "")
                        .font(.body)
                        .fontWeight(.medium)
                        .lineLimit(2)
                    
                    Button(action: onSpecTapped) {
                        HStack {
                            if let spec = item.productInfo?.spec, !spec.isEmpty {
                                Text(spec)
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                                    .lineLimit(1)
                            } else {
                                Text("选择规格")
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                            }
                            
                            Image(systemName: "chevron.right")
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                    }
                    
                    Spacer()
                    
                    HStack {
                        Text("¥\(String(format: "%.2f", item.productInfo?.price ?? 0))")
                            .font(.body)
                            .fontWeight(.semibold)
                            .foregroundColor(.red)
                        
                        Spacer()
                        
                        // 数量控制器
                        QuantityControlView(
                            quantity: item.cartNum,
                            onChanged: onQuantityChanged
                        )
                    }
                }
                
                Spacer()
            }
            .padding(12)
        }
        .background(Color.white)
        .clipShape(RoundedRectangle(cornerRadius: 12))
        .shadow(color: Color.black.opacity(0.05), radius: 2, x: 0, y: 1)
    }
}

// MARK: - 无效商品视图
struct InvalidCartItemView: View {
    let item: CartItem
    
    var body: some View {
        HStack(spacing: 12) {
            // 商品图片
            AsyncImage(url: URL(string: item.productInfo?.image ?? "")) { image in
                image
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .opacity(0.6)
            } placeholder: {
                Rectangle()
                    .fill(Color.gray.opacity(0.2))
            }
            .frame(width: 80, height: 80)
            .clipShape(RoundedRectangle(cornerRadius: 8))
            
            // 商品信息
            VStack(alignment: .leading, spacing: 4) {
                Text(item.productInfo?.storeName ?? "")
                    .font(.body)
                    .fontWeight(.medium)
                    .foregroundColor(.gray)
                    .lineLimit(2)
                
                if let spec = item.productInfo?.spec, !spec.isEmpty {
                    Text(spec)
                        .font(.caption)
                        .foregroundColor(.gray)
                        .lineLimit(1)
                }
                
                Spacer()
                
                Text("商品已失效")
                    .font(.caption)
                    .foregroundColor(.red)
            }
            
            Spacer()
        }
        .padding(12)
        .background(Color.white)
    }
}

// MARK: - 数量控制视图
struct QuantityControlView: View {
    let quantity: Int
    let onChanged: (Int) -> Void
    
    var body: some View {
        HStack(spacing: 0) {
            Button(action: {
                if quantity > 1 {
                    onChanged(quantity - 1)
                }
            }) {
                Image(systemName: "minus")
                    .font(.system(size: 14))
                    .foregroundColor(quantity > 1 ? .primary : .gray)
                    .frame(width: 28, height: 28)
                    .background(Color.white)
                    .overlay(
                        RoundedRectangle(cornerRadius: 4)
                            .stroke(Color.gray.opacity(0.3), lineWidth: 1)
                    )
            }
            .disabled(quantity <= 1)
            
            Text("\(quantity)")
                .font(.body)
                .frame(width: 36, height: 28)
                .background(Color.white)
                .overlay(
                    Rectangle()
                        .stroke(Color.gray.opacity(0.3), lineWidth: 1)
                )
            
            Button(action: {
                onChanged(quantity + 1)
            }) {
                Image(systemName: "plus")
                    .font(.system(size: 14))
                    .foregroundColor(.primary)
                    .frame(width: 28, height: 28)
                    .background(Color.white)
                    .overlay(
                        RoundedRectangle(cornerRadius: 4)
                            .stroke(Color.gray.opacity(0.3), lineWidth: 1)
                    )
            }
        }
    }
}

// MARK: - 规格选择弹窗
struct ProductSpecSelectionView: View {
    let item: CartItem
    let onSpecSelected: (String) -> Void
    @Environment(\.presentationMode) var presentationMode
    @State private var selectedSpec: String
    
    init(item: CartItem, onSpecSelected: @escaping (String) -> Void) {
        self.item = item
        self.onSpecSelected = onSpecSelected
        self._selectedSpec = State(initialValue: item.productInfo?.spec ?? "")
    }
    
    var body: some View {
        VStack(spacing: 0) {
            // 顶部标题栏
            HStack {
                Button(action: {
                    presentationMode.wrappedValue.dismiss()
                }) {
                    Image(systemName: "xmark")
                        .font(.system(size: 16))
                        .foregroundColor(.gray)
                }
                
                Spacer()
                
                Text("选择规格")
                    .font(.headline)
                
                Spacer()
                
                Button(action: {
                    presentationMode.wrappedValue.dismiss()
                }) {
                    Text("")
                        .frame(width: 16)
                }
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 12)
            
            Divider()
            
            // 商品信息
            HStack(spacing: 12) {
                // 商品图片
                AsyncImage(url: URL(string: item.productInfo?.image ?? "")) { image in
                    image
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                } placeholder: {
                    Rectangle()
                        .fill(Color.gray.opacity(0.2))
                }
                .frame(width: 80, height: 80)
                .clipShape(RoundedRectangle(cornerRadius: 8))
                
                VStack(alignment: .leading, spacing: 4) {
                    Text(item.productInfo?.storeName ?? "")
                        .font(.body)
                        .fontWeight(.medium)
                        .lineLimit(2)
                    
                    Text("¥\(String(format: "%.2f", item.productInfo?.price ?? 0))")
                        .font(.body)
                        .fontWeight(.semibold)
                        .foregroundColor(.red)
                    
                    Text("库存: \(0)")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
                
                Spacer()
            }
            .padding(16)
            
            Divider()
            
            // 规格选择区域
            ScrollView {
                VStack(alignment: .leading, spacing: 16) {
                    Text("规格")
                        .font(.headline)
                        .padding(.horizontal, 16)
                        .padding(.top, 16)
                    
                    // 这里应该根据实际商品规格动态生成，这里简化处理
                    LazyVGrid(columns: [GridItem(.adaptive(minimum: 100))], spacing: 12) {
                        ForEach(["默认", "规格1", "规格2", "规格3"], id: \.self) { spec in
                            Button(action: {
                                selectedSpec = spec
                            }) {
                                Text(spec)
                                    .font(.system(size: 14))
                                    .padding(.horizontal, 12)
                                    .padding(.vertical, 8)
                                    .foregroundColor(selectedSpec == spec ? .white : .primary)
                                    .background(selectedSpec == spec ? Color.blue : Color.white)
                                    .cornerRadius(4)
                                    .overlay(
                                        RoundedRectangle(cornerRadius: 4)
                                            .stroke(selectedSpec == spec ? Color.blue : Color.gray.opacity(0.3), lineWidth: 1)
                                    )
                            }
                        }
                    }
                    .padding(.horizontal, 16)
                }
            }
            
            Spacer()
            
            // 底部确认按钮
            Button(action: {
                onSpecSelected(selectedSpec)
                presentationMode.wrappedValue.dismiss()
            }) {
                Text("确定")
                    .font(.headline)
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 14)
                    .background(Color.red)
                    .cornerRadius(8)
            }
            .padding(16)
        }
    }
}

// MARK: - 推荐商品视图
struct RecommendedProductsView: View {
    // 接收推荐商品数据
    let products: [Product]
    
    init(products: [Product]) {
        self.products = products
    }
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Spacer()
                
                // 添加装饰性元素
                Image(systemName: "sparkles")
                    .foregroundColor(.pink)
                
                Text("热门推荐")
                    .font(.headline)
                    .fontWeight(.medium)
                
                Image(systemName: "sparkles")
                    .foregroundColor(.pink)
                
                Spacer()
            }
            .padding(.vertical, 8)
            .background(Color.white)
            
            LazyVGrid(columns: [
                GridItem(.flexible(), spacing: 12),
                GridItem(.flexible(), spacing: 12)
            ], spacing: 16) {
                ForEach(products, id: \.id) { product in
                        Button(action: {
                            // 这里可以添加导航到商品详情的逻辑
                            print("点击了商品: \(product.id)")
                        }) {
                            RecommendedProductCardView(product: product)
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
            }
            .padding(.horizontal, 16)
            .padding(.bottom, 16)
        }
        .background(Color.white)
    }
}

// MARK: - 推荐商品卡片视图
struct RecommendedProductCardView: View {
    let product: Product
    
    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            // 商品图片
            AsyncImage(url: URL(string: product.image ?? "")) { image in
                image
                    .resizable()
                    .aspectRatio(contentMode: .fill)
            } placeholder: {
                Rectangle()
                    .fill(Color.gray.opacity(0.2))
            }
            .frame(height: 140)
            .clipShape(RoundedRectangle(cornerRadius: 8))
            
            // 商品信息
            VStack(alignment: .leading, spacing: 4) {
                Text(product.storeName ?? "")
                    .font(.caption)
                    .fontWeight(.medium)
                    .lineLimit(1)
                    .multilineTextAlignment(.leading)
                
                Text(product.storeName ?? "")
                    .font(.caption)
                    .lineLimit(1)
                    .foregroundColor(.secondary)
                
                HStack(spacing: 4) {
                    Text("¥\(String(format: "%.0f", product.price))")
                        .font(.body)
                        .fontWeight(.semibold)
                        .foregroundColor(.red)
                    
                    if (product.otPrice ?? 0) > product.price {
                        Text("¥\(String(format: "%.0f", product.otPrice ?? 0))")
                            .font(.caption)
                            .foregroundColor(.secondary)
                            .strikethrough()
                    }
                    
                    Spacer()
                    
                    // 销量标签
                    Text("已售\(product.sales ?? 0)")
                        .font(.caption2)
                        .foregroundColor(.white)
                        .padding(.horizontal, 6)
                        .padding(.vertical, 2)
                        .background(Color.orange)
                        .cornerRadius(4)
                }
            }
            .padding(.horizontal, 8)
            .padding(.bottom, 8)
        }
        .background(Color.white)
        .clipShape(RoundedRectangle(cornerRadius: 12))
        .shadow(color: Color.black.opacity(0.05), radius: 2, x: 0, y: 1)
    }
}

// MARK: - 数量选择器
struct QuantitySelectorView: View {
    let quantity: Int
    let onQuantityChange: (Int) -> Void
    
    var body: some View {
        HStack(spacing: 0) {
            // 减少按钮
            Button(action: {
                if quantity > 1 {
                    onQuantityChange(quantity - 1)
                }
            }) {
                Image(systemName: "minus")
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(quantity > 1 ? .primary : .gray)
            }
            .frame(width: 32, height: 32)
            .background(Color.gray.opacity(0.1))
            .cornerRadius(16, corners: [.topLeft, .bottomLeft])
            .disabled(quantity <= 1)
            
            // 数量显示
            Text("\(quantity)")
                .font(.system(size: 14, weight: .medium))
                .foregroundColor(.primary)
                .frame(width: 40, height: 32)
                .background(Color.gray.opacity(0.05))
            
            // 增加按钮
            Button(action: {
                onQuantityChange(quantity + 1)
            }) {
                Image(systemName: "plus")
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(.primary)
            }
            .frame(width: 32, height: 32)
            .background(Color.gray.opacity(0.1))
            .cornerRadius(16, corners: [.topRight, .bottomRight])
        }
        .overlay(
            RoundedRectangle(cornerRadius: 16)
                .stroke(Color.gray.opacity(0.2), lineWidth: 1)
        )
    }
}

// MARK: - 底部结算栏
struct CartBottomBarView: View {
    let totalPrice: Double
    let selectedCount: Int
    let allSelected: Bool
    let isEditing: Bool
    let onSelectAll: () -> Void
    let onCheckout: () -> Void
    let onDeleteSelected: () -> Void
    
    var body: some View {
        VStack(spacing: 0) {
            Divider()
            
            HStack(spacing: 16) {
                // 全选按钮
                Button(action: onSelectAll) {
                    HStack(spacing: 8) {
                        Image(systemName: allSelected ? "checkmark.circle.fill" : "circle")
                            .foregroundColor(allSelected ? .red : .gray)
                            .font(.system(size: 20))
                        
                        Text("全选")
                            .font(.system(size: 16))
                            .foregroundColor(.primary)
                    }
                }
                
                Spacer()
                
                if !isEditing {
                    // 价格显示
                    VStack(alignment: .trailing, spacing: 2) {
                        HStack(alignment: .bottom, spacing: 2) {
                            Text("合计: ¥")
                                .font(.system(size: 14))
                                .foregroundColor(.primary)
                            
                            Text(String(format: "%.2f", totalPrice))
                                .font(.system(size: 20, weight: .semibold))
                                .foregroundColor(.red)
                        }
                        
                        if selectedCount > 0 {
                            Text("已选 \(selectedCount) 件")
                                .font(.system(size: 12))
                                .foregroundColor(.gray)
                        }
                    }
                    
                    // 结算按钮
                    Button(action: onCheckout) {
                        Text("结算(\(selectedCount))")
                            .font(.system(size: 16, weight: .medium))
                            .foregroundColor(.white)
                            .padding(.horizontal, 24)
                            .padding(.vertical, 12)
                            .background(selectedCount > 0 ? Color.red : Color.gray)
                            .cornerRadius(22)
                    }
                    .disabled(selectedCount == 0)
                } else {
                    // 删除按钮
                    Button(action: onDeleteSelected) {
                        Text("删除(\(selectedCount))")
                            .font(.system(size: 16, weight: .medium))
                            .foregroundColor(.white)
                            .padding(.horizontal, 24)
                            .padding(.vertical, 12)
                            .background(selectedCount > 0 ? Color.red : Color.gray)
                            .cornerRadius(22)
                    }
                    .disabled(selectedCount == 0)
                }
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 12)
        }
        .background(Color.white)
    }
}

// MARK: - 空购物车视图
struct EmptyCartView: View {
    var body: some View {
        VStack(spacing: 24) {
            Spacer()
            
            // 空购物车图标
            Image("noshoper")
                .resizable()
                .scaledToFit()
                .frame(width: 100, height: 100)
                .foregroundColor(.gray.opacity(0.5))
            
            VStack(spacing: 8) {
                Text("购物车为空哦～")
                    .font(.system(size: 18, weight: .medium))
                    .foregroundColor(.primary)
                
              
            }
            
            
            
            Spacer()
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.gray.opacity(0.1))
    }
}

// MARK: - 扩展：圆角
extension View {
    func cornerRadius(_ radius: CGFloat, corners: RectCorner) -> some View {
        clipShape(RoundedCorner(radius: radius, corners: corners))
    }
}

struct RectCorner: OptionSet {
    let rawValue: Int
    
    static let topLeft = RectCorner(rawValue: 1 << 0)
    static let topRight = RectCorner(rawValue: 1 << 1)
    static let bottomLeft = RectCorner(rawValue: 1 << 2)
    static let bottomRight = RectCorner(rawValue: 1 << 3)
    
    static let allCorners: RectCorner = [.topLeft, .topRight, .bottomLeft, .bottomRight]
}

struct RoundedCorner: Shape {
    var radius: CGFloat = .infinity
    var corners: RectCorner = .allCorners

    func path(in rect: CGRect) -> Path {
        var path = Path()
        
        let topLeft = corners.contains(.topLeft) ? radius : 0
        let topRight = corners.contains(.topRight) ? radius : 0
        let bottomLeft = corners.contains(.bottomLeft) ? radius : 0
        let bottomRight = corners.contains(.bottomRight) ? radius : 0
        
        path.move(to: CGPoint(x: rect.minX + topLeft, y: rect.minY))
        
        // Top edge and top-right corner
        path.addLine(to: CGPoint(x: rect.maxX - topRight, y: rect.minY))
        if topRight > 0 {
            path.addArc(center: CGPoint(x: rect.maxX - topRight, y: rect.minY + topRight),
                       radius: topRight,
                       startAngle: Angle(degrees: -90),
                       endAngle: Angle(degrees: 0),
                       clockwise: false)
        }
        
        // Right edge and bottom-right corner
        path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY - bottomRight))
        if bottomRight > 0 {
            path.addArc(center: CGPoint(x: rect.maxX - bottomRight, y: rect.maxY - bottomRight),
                       radius: bottomRight,
                       startAngle: Angle(degrees: 0),
                       endAngle: Angle(degrees: 90),
                       clockwise: false)
        }
        
        // Bottom edge and bottom-left corner
        path.addLine(to: CGPoint(x: rect.minX + bottomLeft, y: rect.maxY))
        if bottomLeft > 0 {
            path.addArc(center: CGPoint(x: rect.minX + bottomLeft, y: rect.maxY - bottomLeft),
                       radius: bottomLeft,
                       startAngle: Angle(degrees: 90),
                       endAngle: Angle(degrees: 180),
                       clockwise: false)
        }
        
        // Left edge and top-left corner
        path.addLine(to: CGPoint(x: rect.minX, y: rect.minY + topLeft))
        if topLeft > 0 {
            path.addArc(center: CGPoint(x: rect.minX + topLeft, y: rect.minY + topLeft),
                       radius: topLeft,
                       startAngle: Angle(degrees: 180),
                       endAngle: Angle(degrees: 270),
                       clockwise: false)
        }
        
        return path
    }
}

struct CartView_Previews: PreviewProvider {
    static var previews: some View {
        CartView()
    }
}
